import React, { useRef } from 'react';
import { SearchOutlined } from '@ant-design/icons';
import type { InputRef, TableColumnType } from 'antd';
import { Button, Input, Space } from 'antd';
import type { FilterDropdownProps } from 'antd/es/table/interface';
import { isString } from 'lodash-es';

type DataType = Record<string, any>;
type DataIndex = keyof DataType;

export function useColumnSearch() {
  const searchInput = useRef<InputRef>(null);

  const handleSearch = (
    _selectedKeys: string[],
    confirm: FilterDropdownProps['confirm'],
  ) => {
    confirm();
  };

  const handleReset = (clearFilters: () => void) => {
    clearFilters();
  };

  const getColumnSearchProps = (
    dataIndex: DataIndex,
  ): TableColumnType<DataType> => ({
    filterDropdown: ({
      setSelectedKeys,
      selectedKeys,
      confirm,
      clearFilters,
    }) => (
      <div style={{ padding: 8 }} onKeyDown={(e) => e.stopPropagation()}>
        <Input
          ref={searchInput}
          value={selectedKeys[0]}
          onChange={(e) =>
            setSelectedKeys(e.target.value ? [e.target.value] : [])
          }
          onPressEnter={() => handleSearch(selectedKeys as string[], confirm)}
          style={{ marginBottom: 8, display: 'block' }}
        />
        <Space>
          <Button
            type="primary"
            onClick={() => handleSearch(selectedKeys as string[], confirm)}
            icon={<SearchOutlined />}
            size="small"
            style={{ width: 90 }}
          >
            搜索
          </Button>
          <Button
            onClick={() => clearFilters && handleReset(clearFilters)}
            size="small"
            style={{ width: 90 }}
          >
            重置
          </Button>
        </Space>
      </div>
    ),
    filterIcon: (filtered: boolean) => (
      <SearchOutlined style={{ color: filtered ? '#1677ff' : undefined }} />
    ),
    onFilter: (value, record) =>
      record[dataIndex]
        .toString()
        .toLowerCase()
        .includes((value as string).toLowerCase()),
    onFilterDropdownOpenChange: (visible) => {
      if (visible) {
        setTimeout(() => searchInput.current?.select(), 100);
      }
    },
  });

  return { getColumnSearchProps };
}

export function transformColumns(
  columns: TableColumnType<DataType>[],
  searchDataIndexs: DataIndex[],
  transform?: (
    searchDataIndex: DataIndex,
    column: TableColumnType<DataType>,
  ) => TableColumnType<DataType>,
) {
  return columns.map((column) => {
    const { dataIndex } = column;
    if (
      !dataIndex ||
      !isString(dataIndex) ||
      !searchDataIndexs.includes(dataIndex)
    )
      return column;
    return {
      ...column,
      ...transform?.(dataIndex, column),
    };
  });
}
